package leetCode.ergodic;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 两数之和
 */
public class TwoSum {


    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 5, 6, 8};
        int target = 10;
        long begin = getmicTime();
        System.out.println(Arrays.toString(twoSum(nums, target)));
        long end = getmicTime();
        System.out.println(end - begin);

        begin = getmicTime();
        System.out.println(Arrays.toString(twoSum2(nums, target)));
        end = getmicTime();
        System.out.println(end - begin);

        begin = getmicTime();
        System.out.println(Arrays.toString(twoSum3(nums, target)));
        end = getmicTime();
        System.out.println(end - begin);
    }


    /**
     * 暴力递归
     * @param nums
     * @param target
     * @return
     */
    public static int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i+1; j < nums.length; j++) {
                if(nums[i] + nums[j] == target){
                    return new int[] {i, j};
                }
            }
        }
        return null;
    }


    /**
     * 用hash表,增加空间复杂,减少时间复杂,
     * 这里的写法不是最优(可以将第一个循环去掉)
     * @param nums
     * @param target
     * @return
     */
    public static int[] twoSum2(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
        }
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement) && map.get(complement) != i) {
                return new int[] { i, map.get(complement) };
            }
        }
        throw null;
    }


    /**
     * 同样是用空间复杂,降低时间的复杂,但是这里还是有疑问,如果数组长度超过2048会不会有问题
     * @param nums
     * @param target
     * @return
     */
    public static int[] twoSum3(int[] nums, int target) {
        int volume =2048; //100000000000
        int bitMode = volume-1;
        //011111111111
        int [] result =new int[volume];

        for (int i=0;i<nums.length;i++){
            int c = (target - nums[i]) & bitMode;
            if (result[c]!=0){
                return new int[]{result[c]-1,i};
            }
            result[nums[i] & bitMode]=i+1;
        }
        return null;
    }


    public static Long getmicTime() {
        Long cutime = System.currentTimeMillis() * 1000; // 微秒
        Long nanoTime = System.nanoTime(); // 纳秒
        return cutime + (nanoTime - nanoTime / 1000000 * 1000000) / 1000;
    }
}
